import axios from "axios";
import { Message, Loading } from 'element-ui';
let	loading = null

import {
  handleChangeRequestHeader,
  handleConfigureAuth,
  handleAuthError,
  handleGeneralError,
  handleNetworkError,
} from "./tools";
const baseURL = process.env.NODE_ENV === "development"? '/' : '/'

// 创建 axios 实例
const http = axios.create({
	baseURL,
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' },
});

http.interceptors.request.use((config) => {
  config = handleChangeRequestHeader(config);
  config = handleConfigureAuth(config);
  loading=Loading.service({
    lock: true,
    text: 'loading……',
    background: 'rgba(0, 0, 0, 0.7)'
})
  return config;
});

http.interceptors.response.use(
  (response) => {
    // console.log('*********', response, response.data);
		loading.close()

    if (response.status !== 200) return Promise.reject(response.data);
    if(response.data.code === 0) {
      // handleAuthError(response.data.errno);
      // Message.success(response.data.message)
    } else {
      handleGeneralError(response.data.code, response.data.message, response);
      // const loading = Loading.service({
      //   lock: true,
      //   text: i18n.t('httpMsg.tokenExpired'),
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)'
      // })
    }
    return response;
  },
  (err) => {
		loading.close()
    handleNetworkError(err.response.status);
    Promise.reject(err.response);
  }
);

export const LoadingGet = (url, params = {}, clearFn) =>
  new Promise((resolve) => {
    http
      .get(url, { params })
      .then((result) => {
        let res;
        if (clearFn !== undefined) {
          res = clearFn(result.data);
        } else {
          res = result.data;
        }
        resolve([null, res]);
      })
      .catch((err) => {
        resolve([err, undefined]);
      });
  });

export const LoadingPost = (url, data, params = {}) => {
  return new Promise((resolve) => {
    http
      .post(url, data, { params })
      .then((result) => {
        resolve([null, result.data]);
      })
      .catch((err) => {
        resolve([err, undefined]);
      });
  });
};
export const LoadingPut = (url, data, params = {}) => {
  return new Promise((resolve) => {
    http
      .put(url, data, { params })
      .then((result) => {
        resolve([null, result.data]);
      })
      .catch((err) => {
        resolve([err, undefined]);
      });
  });
};

export const Delete = (url, data, params = {}) => {
  return new Promise((resolve) => {
    http
      .delete(url, data, { params })
      .then((result) => {
        resolve([null, result.data]);
      })
      .catch((err) => {
        resolve([err, undefined]);
      });
  });
};
